package com.xiangshizhineng.tianzhangzhi.app.common.base;

import com.alibaba.fastjson.JSONObject;
import com.xiangshizhineng.tianzhangzhi.app.utils.JwtUtils;
import com.xiangshizhineng.tianzhangzhi.app.utils.SnowflakeUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

public class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> {

    @Override
    public T packAddBaseProps(T base, HttpServletRequest request) {
        return base;
    }

    @Override
    public JSONObject packAddJSONObjectProps(JSONObject json, HttpServletRequest request) {
        return json;
    }

    @Override
    public T packModifyBaseProps(T base, HttpServletRequest request) {
        return base;
    }

    @Override
    public Long getUserId(HttpServletRequest request) {
        // 通过token获取操作人id
        Long id = 0L;
        if (request != null) {
            String jwt = request.getHeader("Authorization");
            if (StringUtils.isNotEmpty(jwt)) {
                id = JwtUtils.getId(jwt.replace("Bearer ", ""));
            }
        }
        return id;
    }

    @Override
    public String getIp(HttpServletRequest request) {
        String ip = "127.0.0.1";
        if (request != null) {
            ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        return ip;
    }

    /**
     * 获取当前语言，默认保持英文
     *
     * @param request
     * @return
     */
    public Locale getLang(HttpServletRequest request) {
        Locale lang = Locale.US;
        // 获取当前语言
        if (request != null) {
            String headerLang = request.getHeader("lang");
            if (headerLang != null) {
                if ("zh-CN".equals(headerLang)) {
                    lang = Locale.SIMPLIFIED_CHINESE;
                }
            }
        }
        return lang;
    }
}
